package com.lam.system.service.impl;

import java.text.MessageFormat;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lam.common.components.easyexcel.imp.model.AbstractImportBody;
import com.lam.common.components.easyexcel.imp.model.ImportEntry;
import com.lam.common.components.easyexcel.imp.model.ImportWrapper;
import com.lam.common.components.easyexcel.imp.service.AbstractImportService;
import com.lam.common.components.lang.LangConstant;
import com.lam.common.components.lang.LangService;
import com.lam.common.exception.BusinessException;
import com.lam.common.utils.CollectionUtil;
import com.lam.common.utils.JsonUtil;
import com.lam.common.utils.StringUtils;
import com.lam.system.entity.SysLanguage;
import com.lam.system.entity.imp.SysLanguageImp;
import com.lam.system.mapper.SysLanguageMapper;
import com.lam.system.param.SysLanguageParam;
import com.lam.system.service.SysLanguageService;

/**
 * 国际化管理Service业务层处理
 * 
 * @author admin
 * @date 2022-08-31
 */
@Service
public class SysLanguageServiceImpl extends AbstractImportService<SysLanguageImp, SysLanguage> implements SysLanguageService, LangService {

    @Autowired
    private SysLanguageMapper sysLanguageMapper;
	
	@Override
	@Cacheable(value = LangConstant.SYS_ENABLE_LANG_CACHE, key = "#root.args[0] + ':' + #root.args[1] + ':' + #root.args[2]", unless = "#result == null ")
	public String getLangValueByKey(String lang, String category, String key) {
		SysLanguage lan = getLangByKey(lang, category, key);
		return lan == null?null:lan.getValue();
	}
	
	@Override
	public SysLanguage getLangByKey(String lang, String category, String key) {
		
		if(StringUtils.isContainChinese(key) || StringUtils.isBlank(key)){
			return null;
		}
		if(!StringUtils.contains(key, ".")){
			//默认后端提示语
			key = "errorTip." + key;
		}
		
		String[] ss = key.split("[.]");
		QueryWrapper<SysLanguage> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("lang", lang);
		queryWrapper.eq("category", category);
		queryWrapper.eq("type", ss[0]);
		queryWrapper.eq("lang_key", ss[1]);
		List<SysLanguage> list = sysLanguageMapper.selectList(queryWrapper);
		if(CollectionUtil.isEmpty(list)) {
			return null;
		}
		return list.get(0);		
	}
	
	
    /**
     * 查询国际化管理
     * 
     * @param id ID
     * @return 单个对象
     */
    @Override
    @Transactional(readOnly = true)
    public SysLanguage selectById(String id) {

        return sysLanguageMapper.selectById(id);
    }

    /**
     * 查询国际化管理列表
     * 
     * @param param
     * @return 
     */
    @Override
    @Transactional(readOnly = true)
    public List<SysLanguage> selectList(SysLanguageParam param) {
    
        QueryWrapper<SysLanguage> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(StringUtils.isNotBlank(param.getCategory()), "category", param.getCategory());
        queryWrapper.eq(StringUtils.isNotBlank(param.getType()), "type", param.getType());
        queryWrapper.like(StringUtils.isNotBlank(param.getLangKeyKey()), "lang_key", param.getLangKeyKey());
        queryWrapper.eq(StringUtils.isNotBlank(param.getLangKey()), "lang_key", param.getLangKey());
        queryWrapper.like(StringUtils.isNotBlank(param.getValueKey()), "value", param.getValueKey());
        queryWrapper.eq(StringUtils.isNotBlank(param.getValue()), "value", param.getValue());
        queryWrapper.eq(StringUtils.isNotBlank(param.getLang()), "lang", param.getLang());

        return sysLanguageMapper.selectList(queryWrapper);
    }

    /**
     * 新增国际化管理
     * 
     * @param sysLanguage 
     * @return 
     */
    @Override
    @CacheEvict(value = LangConstant.SYS_ENABLE_LANG_CACHE, allEntries=true)
    @Transactional
    public int insert(SysLanguage sysLanguage) {
    
    	QueryWrapper<SysLanguage> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("category", sysLanguage.getCategory());
		queryWrapper.eq("lang_key", sysLanguage.getLangKey());
		queryWrapper.eq("type", sysLanguage.getType());
		List<SysLanguage> list = sysLanguageMapper.selectList(queryWrapper);
		if(CollectionUtil.isNotEmpty(list)){
			throw new BusinessException("errorTip.existKeyError");
		}
		
		List<Map<String, Object>> arr = JsonUtil.parseArray(sysLanguage.getValue());
		int n = 0;
		for (Map<String, Object> map : arr) {
			sysLanguage.setId(null);
			sysLanguage.setLang(JsonUtil.getString(map, "lang"));
			sysLanguage.setValue(JsonUtil.getString(map, "value"));
			n += sysLanguageMapper.insert(sysLanguage);
		}
        return n;
    }

    /**
     * 修改国际化管理
     * 
     * @param sysLanguage 
     * @return 
     */
    @Override
    @CacheEvict(value = LangConstant.SYS_ENABLE_LANG_CACHE, allEntries=true)
    @Transactional
    public int update(SysLanguage sysLanguage) {
    
    	SysLanguage orig = sysLanguageMapper.selectById(sysLanguage.getId());
		if(orig == null) {
			throw new BusinessException("errorTip.notExistRecord");
		}
		
		QueryWrapper<SysLanguage> queryWrapper = new QueryWrapper<>();
		
		queryWrapper.eq("category", orig.getCategory());
		queryWrapper.eq("lang_key", orig.getLangKey());
		queryWrapper.eq("type", orig.getType());
		List<SysLanguage> list = sysLanguageMapper.selectList(queryWrapper);
		
		queryWrapper = new QueryWrapper<>();
		queryWrapper.notIn("id", CollectionUtil.getPropertySet(list, "id"));
		queryWrapper.eq("category", sysLanguage.getCategory());
		queryWrapper.eq("lang_key", sysLanguage.getLangKey());
		queryWrapper.eq("type", sysLanguage.getType());
		List<SysLanguage> exisList = sysLanguageMapper.selectList(queryWrapper);
		if(CollectionUtil.isNotEmpty(exisList)){
			throw new BusinessException("errorTip.existKeyError");
		}
		
		Map<String, SysLanguage> langMap = CollectionUtil.getMapByProperty(list, "lang");
		List<Map<String, Object>> arr = JsonUtil.parseArray(sysLanguage.getValue());
		int n = 0;
		for (Map<String, Object> map : arr) {
			if(StringUtils.isBlank(JsonUtil.getString(map, "value"))) {
				continue;
			}
			SysLanguage tmpEntity = langMap.get(JsonUtil.getString(map, "lang"));
			if(tmpEntity == null) {
				sysLanguage.setId(null);
				sysLanguage.setLang(JsonUtil.getString(map, "lang"));
				sysLanguage.setValue(JsonUtil.getString(map, "value"));
				n += sysLanguageMapper.insert(sysLanguage);
			}else {
				tmpEntity.setCategory(sysLanguage.getCategory());
				tmpEntity.setType(sysLanguage.getType());
				tmpEntity.setLangKey(sysLanguage.getLangKey());
				tmpEntity.setValue(JsonUtil.getString(map, "value"));
				n += sysLanguageMapper.updateById(tmpEntity);
			}
		}
		return n;		
    }

    /**
     * 删除国际化管理信息
     * 
     * @param idStr ID，多个用逗号分隔
     * @return 
     */
    @Override
    @Transactional
    public int deleteById(String idStr) {
    	if(StringUtils.isBlank(idStr)) {
            return 0;
    	}
    	int n = 0;
    	for (String id : StringUtils.str2List(idStr)) {
            n += sysLanguageMapper.deleteById(id);
        }
        return n;
    }
    
    /**
     * 导入国际化管理数据
     * @param dataList 国际化管理数据列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @return 保存失败的记录
     */
    @Override
    @Transactional
    public void importData(ImportWrapper<SysLanguageImp, SysLanguage> wrapper) {
        
    	QueryWrapper<SysLanguage> queryWrapper = new QueryWrapper<>();
    	
    	importData(wrapper, new AbstractImportBody<SysLanguageImp, SysLanguage>() {

			@Override
			public SysLanguage selectRecord(ImportEntry<SysLanguageImp, SysLanguage> entry) {
				queryWrapper.clear();
				queryWrapper.select("id").last("limit 1");
				queryWrapper.eq("category", entry.getData().getCategory());
        		queryWrapper.eq("lang_key", entry.getData().getLangKey());
        		queryWrapper.eq("type", entry.getData().getType());
				return sysLanguageMapper.selectOne(queryWrapper);
			}
			@Override
			public int insertData(SysLanguage data) {
				return insert(data);
			}
			@Override
			public int updateData(SysLanguage data) {
				return update(data);
			}
			@Override
			public String notUniqueMsg(ImportEntry<SysLanguageImp, SysLanguage> entry) {
				return MessageFormat.format("关键字【{0}】已存在", entry.getData().getLangKey());
			}
    	});
    }
    
}
